package com.algorithm.binarysearchnorecursion;

/**
 * @author xxy
 * @create 2021 3 25 8:33
 */
public class BinarySearchNoRecur {
    public static void main(String[] args) {
        int[] arr={1,3,4,5,6,7,8,88,99,999};
        System.out.println(binarySearch(arr,88));
    }

    //二分查找的非递归实现
    public static int binarySearch(int[] arr, int target) {
        int left=0;
        int right=arr.length-1;
        while (left<=right){//继续查找
            int mid = (left + right)/2;
            if(arr[mid]==target){
                return mid;
            }else if(arr[mid]>target){
                right=mid-1;
            }else {
                left=mid+1;
            }
        }
        return -1;
    }
}
